<template>
  <s-clean-layout navbar="none" tabbar="/pages/index/message">
    <view class="page-container">
      <!-- 固定顶部区域 -->
      <view class="fixed-header">
        <!-- 状态栏占位 -->
        <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
      <!-- 导航栏 - 修改为白色背景 -->
      <view class="custom-nav">
        <view class="nav-left">
          <text class="title">消息</text>
          <view class="count-wrapper">
            <text class="count">({{ unreadCount }})</text>
            <!-- 添加清理图标 -->
            <view class="clear-btn" @tap="clearUnread">
              <uni-icons type="trash" size="16" color="#666"></uni-icons>
            </view>
          </view>
        </view>
      </view>

      <!-- 搜索栏 -->
      <view class="search-bar">
        <uni-icons type="search" size="20" color="#666"></uni-icons>
        <input 
          class="search-input" 
          v-model="searchContent"
          placeholder="搜索消息"
          confirm-type="search"
          @confirm="onSearch"
          @input="onSearchInput"
        />
        <view class="clear-search" v-if="searchContent" @tap="clearSearch">
          <uni-icons type="clear" size="16" color="#999"></uni-icons>
        </view>
      </view>
      </view>



      <!-- 可滚动内容区域 -->
      <view class="scrollable-content">
      <!-- 消息列表 - 添加卡片效果 -->
      <view class="message-content">
        <template v-if="loading">
          <view class="loading">加载中...</view>
        </template>
        
        <template v-else>
          <view class="message-list" v-if="messageList.length > 0">
            <view 
              class="message-item" 
              v-for="(item, index) in messageList" 
              :key="index"
              @tap="onMessageClick(item)"
            >
              <view class="avatar">
                <image :src="getIcon(item.type)" mode="aspectFill" />
              </view>
              <view class="content">
                <view class="title">{{ item.title }}</view>
                <view class="desc">{{ item.desc }}</view>
              </view>
              <view class="right">
                <text class="time">{{ item.time }}</text>
                <view class="badge" v-if="item.unread">{{ item.unread }}</view>
              </view>
            </view>
          </view>
          <view v-else class="empty-tip">
            <text>暂无相关消息</text>
          </view>
        </template>
        </view>
      </view>
    </view>
  </s-clean-layout>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import MessageApi from '@/sheep/api/message/message'
import { onPullDownRefresh } from '@dcloudio/uni-app';
import { formatMessageTime } from '@/sheep/util/date_util';

const loading = ref(true)
const messageList = ref([])
const unreadCount = ref(0)
const searchContent = ref('')
const statusBarHeight = ref(0)
let searchTimer = null

// 获取状态栏高度
uni.getSystemInfo({
  success: (res) => {
    statusBarHeight.value = res.statusBarHeight || 0
  }
})

// 获取未读消息数
const getUnreadCount = async () => {
  try {
    const res = await MessageApi.queryUnReadNoticeNum()
    if (res.code === 0) {
      // 累加所有类型的未读消息数
      unreadCount.value = res.data.reduce((total, item) => total + item.unreadcount, 0)
    }
  } catch (error) {
    console.error('获取未读消息数失败:', error)
  }
}

// 获取消息列表
const getMessageList = async () => {
  loading.value = true
  try {
    const res = await MessageApi.queryUserMessageList({
      readStatus: 0,
      searchContent: searchContent.value,
      pageNum: 1,
      pageSize: 100
    })
    if (res.code === 0) {
      messageList.value = res.data.list.map(item => ({
        id: item.id,
        type: getMessageType(item.businessType),
        title: item.messageTitle,
        desc: item.messageContent,
        time: formatMessageTime(item.createTime),
        unread: item.readStatus === 0 ? 1 : 0,
        actionUrl: item.actionUrl || ''
      }))
    }
  } catch (error) {
    console.error('获取消息列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索输入处理
const onSearchInput = () => {
  // 防抖处理
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  searchTimer = setTimeout(() => {
    getMessageList()
  }, 300)
}

// 搜索确认
const onSearch = () => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  getMessageList()
}

// 清除搜索
const clearSearch = () => {
  searchContent.value = ''
  getMessageList()
}

// 根据业务类型获取消息类型
const getMessageType = (businessType) => {
  const typeMap = {
    'CONTACT_EVENT': 'task',
    'IMPORT_DAY': 'anniversary'
  }
  return typeMap[businessType] || 'default'
}

// Icon mapping
const iconMap = {
  anniversary: '/static/images/icon/memorial.svg',
  task: '/static/images/icon/event.svg',
  default: '/static/images/message/default.png'
}

// Get icon by type with fallback
const getIcon = (type) => {
  return iconMap[type] || iconMap.default
}

const onMessageClick = async (item) => {
  if (!item || !item.id) return
  
  try {
    await MessageApi.readNotice({ id: item.id })
    // 更新消息状态
    const index = messageList.value.findIndex(msg => msg.id === item.id)
    if (index !== -1) {
      messageList.value[index].unread = 0
    }
    // 更新未读消息数
    await getUnreadCount()
    
    // 根据actionUrl进行跳转
    if (item.actionUrl) {
      // 如果是外部链接
      if (item.actionUrl.startsWith('http')) {
        // 使用web-view打开外部链接
        uni.navigateTo({
          url: `/pages/webview/index?url=${encodeURIComponent(item.actionUrl)}`
        })
      } else {
        // 内部页面跳转
        // 解析actionUrl，提取tab参数
        const url = new URL(item.actionUrl, 'http://example.com');
        const contactId = url.searchParams.get('id');
        const businessType = item.type;
        
        // 根据业务类型确定要跳转的标签页索引
        let tabIndex = 0; // 默认显示资料页
        switch (businessType) {
          case 'anniversary':
            tabIndex = 1; // 纪念标签页
            break;
          case 'task':
            tabIndex = 2; // 事件标签页
            break;
        }
        
        // 构建跳转URL，添加tab参数
        const targetUrl = `/pages/contact/detail?id=${contactId}&tab=${tabIndex}`;
        uni.navigateTo({
          url: targetUrl
        });
      }
    } else {
      // 如果没有actionUrl，跳转到默认的消息详情页
      uni.navigateTo({
        url: `/pages/message/detail?type=${item.type}`
      })
    }
  } catch (error) {
    console.error('标记消息已读失败:', error)
  }
}

// 添加清除未读消息方法
const clearUnread = async () => {
  try {
    await MessageApi.readAllNotice()
    // 更新所有消息状态
    messageList.value.forEach(item => {
      item.unread = 0
    })
    // 更新未读消息数
    unreadCount.value = 0
    
    uni.showToast({
      title: '已清除所有未读消息',
      icon: 'success'
    })
  } catch (error) {
    console.error('清除未读消息失败:', error)
  }
}

// 下拉刷新方法
onPullDownRefresh(async () => {
  await getMessageList();
  await getUnreadCount();
  uni.stopPullDownRefresh();
});

// 初始化
onMounted(() => {
  getMessageList()
  getUnreadCount()
});
</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  /* 去除 height: 100% 避免多余滚动 */
  box-sizing: border-box;
  overflow: hidden;
  background-color: #f8f9fc; /* 更柔和的背景色 */
  /* 添加渐变背景 */
  background-image: linear-gradient(to bottom, #f0f4ff, #f8f9fc);
}

/* 状态栏样式 */
.status-bar {
  width: 100%;
  background-color: #f8f9fc;
}

/* 固定顶部区域 */
.fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background-color: #f8f9fc;
  background-image: linear-gradient(to bottom, #f0f4ff, #f8f9fc);
  padding: 20rpx;
  padding-bottom: 0;
}

/* 可滚动内容区域 */
.scrollable-content {
  overflow-y: auto;
  overflow-x: hidden;
  padding: 20rpx;
  padding-top: 0;
  /* 为固定顶部留出空间，包含状态栏+导航栏+搜索栏的高度 */
  margin-top: 260rpx;  /* 状态栏88rpx + 导航栏80rpx + 搜索栏100rpx */
  /* 简化高度控制，让内容自然撑开 */
}

/* 微信小程序专用高度修正 */
/* #ifdef MP-WEIXIN */
.page-container {
  /* 在微信小程序中不使用vh单位，依赖父容器的flex布局 */
  min-height: auto;
}

.scrollable-content {
  /* 微信小程序中调整顶部间距 */
  margin-top: 350rpx;  /* 给更多空间以确保不被遮挡 */
  /* 简化高度控制，让内容自然撑开 */
}
/* #endif */

.custom-nav {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: calc(var(--status-bar-height) + 24rpx) 32rpx 32rpx;
  background: rgba(255, 255, 255, 0.9); /* 半透明效果 */
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 1;
  box-sizing: border-box;
  margin-bottom: 20rpx;
  /* 添加微妙的边框 */
  border: 1rpx solid rgba(230, 235, 245, 0.8);
  
  .nav-left {
    display: flex;
    align-items: center;
    
    .title {
      font-size: 40rpx;
      color: #333;
      font-weight: 600;
      /* 添加文字阴影 */
      text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.05);
    }
    
    .count-wrapper {
      display: flex;
      align-items: center;
      margin-left: 12rpx;
    }
    
    .count {
      font-size: 28rpx;
      color: #666;
      font-weight: 500;
      background: #f0f2f5;
      padding: 4rpx 12rpx;
      border-radius: 20rpx;
    }
    
    .clear-btn {
      margin-left: 8rpx;
      width: 40rpx;
      height: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f0f2f5;
      border-radius: 50%;
      
      &:active {
        background: #e0e0e0;
      }
    }
  }
}

.search-bar {
  background: #fff;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  height: 80rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  border: 1rpx solid rgba(230, 235, 245, 0.8);
  margin: 10rpx 0 20rpx;
  width: 100%;
  box-sizing: border-box;
  
  .search-input {
    flex: 1;
    margin-left: 16rpx;
    font-size: 28rpx;
    color: #333;
    height: 100%;
  }
  
  .clear-search {
    padding: 10rpx;
    margin-left: 10rpx;
  }
  
  &:active {
    opacity: 0.8;
    transform: scale(0.99);
  }
}

.message-content {
  flex: 1;
  background-color: rgba(255, 255, 255, 0.9); /* 半透明效果 */
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  width: 100%;
  box-sizing: border-box;
  overflow: hidden;
  /* 添加微妙的边框 */
  border: 1rpx solid rgba(230, 235, 245, 0.8);
}

.message-list {
  padding: 10rpx 0;
  
  .message-item {
    display: flex;
    align-items: center;
    padding: 20rpx;
    background: #fff;
    border-bottom: 1rpx solid #f5f7fa;
    transition: all 0.2s;
    
    &:active {
      background-color: #f5f7fa;
      transform: scale(0.99);
    }
    
    &:last-child {
      border-bottom: none;
    }
    
    .avatar {
      width: 88rpx;
      height: 88rpx;
      border-radius: 50%;
      overflow: hidden;
      margin-right: 24rpx;
      box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.05);
      border: 2rpx solid rgba(255, 255, 255, 0.8);
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #f5f7fa;
      
      image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
    
    .content {
      flex: 1;
      padding-right: 20rpx;
      
      .title {
        font-size: 32rpx;
        color: #333;
        margin-bottom: 10rpx;
        font-weight: 500;
      }
      
      .desc {
        font-size: 28rpx;
        color: #666;
        width: 420rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        line-height: 1.4;
      }
    }
    
    .right {
      text-align: right;
      min-width: 100rpx;
      
      .time {
        font-size: 24rpx;
        color: #999;
        display: block;
        margin-bottom: 12rpx;
      }
      
      .badge {
        display: inline-block;
        min-width: 36rpx;
        height: 36rpx;
        line-height: 36rpx;
        padding: 0 10rpx;
        background: linear-gradient(135deg, #FF6B6B, #FF4141);
        border-radius: 18rpx;
        font-size: 24rpx;
        color: #fff;
        text-align: center;
        box-shadow: 0 4rpx 8rpx rgba(255, 65, 65, 0.2);
      }
    }
  }
}

.loading {
  padding: 40rpx;
  text-align: center;
  color: #999;
  font-size: 28rpx;
}

.empty-tip {
  padding: 40rpx;
  text-align: center;
  color: #999;
  font-size: 28rpx;
}
</style>